package com.zhu.controller;

import com.zhu.pojo.entity.Article;
import com.zhu.pojo.entity.Category;
import com.zhu.pojo.entity.PageBean;
import com.zhu.pojo.entity.Result;
import com.zhu.service.ArticleService;
import com.zhu.utils.ThreadLocalUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Tag(name = "文章相关")
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @Operation(summary = "文章列表")
    @GetMapping
    public Result<PageBean<Article>> list(Integer pageNum,
                                          Integer pageSize,
                                          @RequestParam(required = false) Integer categoryId,
                                          @RequestParam(required = false) String state) {
        PageBean<Article> pb = articleService.list(pageNum, pageSize, categoryId, state);
        return Result.success(pb);
    }

    @Operation(summary = "新增文章")
    @PostMapping
    public Result add(@RequestBody @Validated Article article) {
        articleService.add(article);
        return Result.success();
    }

    @Operation(summary = "文章详情")
    @GetMapping("/detail")
    public Result<Article> detail(@RequestParam Integer id) {
        Article article = articleService.findById(id);
        return Result.success(article);
    }

    @Operation(summary = "更新文章")
    @PutMapping
    public Result update(@RequestBody Article article) {
        articleService.update(article);
        return Result.success("更新成功");
    }

    @Operation(summary = "删除文章")
    @DeleteMapping
    public Result delete(@RequestParam Integer id) {
        Article article = articleService.findById(id);
        if (article == null) {
            return Result.error(String.format("文章 %s 不存在", id));
        }
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        if (!article.getCreateUser().equals(userId)) {
            return Result.error("用户只能删除由自己创建文章");
        }

        articleService.delete(id);
        return Result.success("删除成功");
    }
}
